package com.neusoft.chh.d1017;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @Author: duan
 * @Date: Create in 11:19 2020/10/14
 */
public class HelloWorldServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();//生命周期有关
        /*
            init方法表示在创建该Servlet时，你需要做些什么，都可以写在init方法中
            初始化方法一般只会执行一次
            为什么不使用HttpServlet的构造方法创建
            因为HttpServlet是应该由Tomcat创建，个人自己创建的不会添加到Tomcat容器中
         */
        System.out.println("Servlet的初始化方法");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);
        System.out.println("处下get请求");
        ServletConfig servletConfig = getServletConfig();
        System.out.println(servletConfig.getServletName());
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            System.out.println(name);
            System.out.println(servletConfig.getInitParameter(name));
        }
        ServletContext context = getServletContext();
        System.out.println(context.getAttribute("name"));
        // 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.println("get success 终于成功了");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
        System.out.println("处下post请求");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        //doGet、doPost都会调用service方法，不推荐写在service方法中
    }

    @Override
    public void destroy() {
        super.destroy();
        //当这个Servlet不再被使用时，就会被销毁
        System.out.println("Servlet销毁方法");//生命周期有关
    }
}
